<template>
  <Modal v-model="modal">
    <p slot="header">加库存(<span class="font-red">填负数可减库存</span>)</p>
    <div>
      <Form :model="form" :label-width="80" ref="form" :rules="rules">
        <FormItem label="加库存" prop="stock">
          <InputNumber v-model="form.stock" precision="0" :min="-9999999" :max="9999999999999999999999"></InputNumber>
        </FormItem>
      </Form>
    </div>
    <div slot="footer">
      <Button @click="modal = false" size="large" type="text">取消</Button>
      <Button :disabled="btnDisabled" @click="onSave" type="primary" size="large">确定</Button>
    </div>
</Modal>
</template>
<script>
export default {
  data() {
    const validateNum = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
          callback(new Error('请输入库存数'))
      } else {
        if (Number(value) + this.lastStock < 0) {
          callback(new Error('总库存数不能低于0'))
        } else {
          callback()
        }
      }
    }
    return {
      id: null,
      modal: false,
      btnDisabled: false,
      lastStock: null,
      rules: {
        stock: [
          { required: true, type: 'number', trigger: 'blur', validator: validateNum }
        ]
      },
      form: {
        stock: null
      }
    };
  },
  methods: {
    resetForm(id, lastStock) {
      this.$refs.form.resetFields();
      this.id = id
      this.lastStock = Number(lastStock)
      this.form = {
        stock: null
      }
      this.btnDisabled = false
      this.openModal()
    },
    openModal() {
      this.modal = true;
    },
    closeModal() {
      this.modal = false;
    },
    onSave() {
      if (this.btnDisabled) return
      this.$refs["form"].validate(valid => {
        if (valid) {
          let param = {
            id: this.id,
            stock: this.form.stock
          }
          this.btnDisabled = true
          this.$ajaxPost('/lottery/prize/add_stock', param).then(data => {
            this.$Notice.success({
              title: `库存修改成功`
            })
            this.$emit('complete')
            this.closeModal()
          }).catch(() => {
            this.btnDisabled = false
          })
        }
      });
    }
  }
}
</script>

